package com.qf.servlet;

import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
//前台用户管理的模块

@WebServlet("/user")
public class UserServlet extends baseServlet {
    public void checkUser(HttpServletRequest request,HttpServletResponse response) throws IOException {

        //接收参数${pageContext.request.contextPath}/check?username="+username+""
        String username = request.getParameter("username");
        //调用前台用户业务接口
        UserService userService = new UserServiceImpl() ;
        boolean flag = userService.checkUser(username);
        //判断是否存在
        if(flag){
            //可以注册
            response.getWriter().write("1");
        }else{
            //不能注册
            response.getWriter().write("0");
        }
    }
    //跳转注册界面
    public void loginUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
    }
    public void registerUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);

    }
    //注册添加用户
    public void UserRegister(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //获取前台验证码的数据
        String usercode = request.getParameter("usercode");
        //从服务器端获得存储的四位数验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        //验证码是一次性验证码,获取一次删除一次,不存储
        session.removeAttribute("CHECKCODE_SERVER");
        //判断,如果不一致,请重新输入,
        if (usercode == null || !usercode.equalsIgnoreCase(checkcode_server)) {
            request.setAttribute("msg", "验证码错误,请重新输入");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request, response);
        } else {
            //验证码如果正确,再获取其他数据
            Map<String, String[]> parameterMap = request.getParameterMap();
       /* String birthday = request.getParameter("birthday");
        System.out.println(birthday);*/
            //封装对象
            User user = new User();
            //封装用户之前,进行类型转换
            ConvertUtils.register(new MyConvert(), Date.class);
            //参数一:convert接口-->自定义一个类,实现convent接口
            //参数2:要转换成什么类型的类的的字节码文件

            try {
                //封装用户,将map集合的value封装到user中
                BeanUtils.populate(user, parameterMap);

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            System.out.println(user);
            //获取User的其他属性
            //UID需要使用工具类UUID生成
            user.setUid(UUIDUtils.getId());
            //密码需要加密--MD5Utils工具类进行加密
            String password = request.getParameter("password");
            user.setPassword(MD5Utils.md5(password));
            //获取激活码,激活码是通过UUID工具产生的
            user.setCode(UUIDUtils.getCode());
            //调用业务接口,获取User实体
            UserService us = new UserServiceImpl();
            System.out.println(user);
            us.registerUser(user);
            //request域中,添加数据
            request.setAttribute("msg", "恭喜您,注册成功,请激活邮箱");
            request.getRequestDispatcher("/jsp/message.jsp").forward(request, response);
        }
    }
    //邮件激活的方法
    public void UserActive(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        UserService userService = new UserServiceImpl();
        User user = userService.findUserByCode(code);
        if(user!= null){
            request.setAttribute("msg","恭喜您,注册成功,<a href='http://localhost:8080/Maven_Project_02_war/user?methodName=userLogin'>请登录</a>");
            request.getRequestDispatcher("/jsp/message.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","对不起,用户激活失败,请重新激活");
            request.getRequestDispatcher("/jsp/message.jsp").forward(request,response) ;
        }
    }
    //用户登录的方法
    public void userLogin(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //获取request域中的参数
        String username = request.getParameter("username");
        //获取密码
        String password = request.getParameter("password");
        //获取request域中的验证码
        String usercode = request.getParameter("usercode");
        //获取服务器中的四位数验证码
        String checkcode_server = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        //判断比较验证码是否正确
        //验证码是一次性验证码
        request.getSession().removeAttribute("CHECKCODE_SERVER");
        if (usercode==null || !usercode.equalsIgnoreCase(checkcode_server)){
            request.setAttribute("msg","验证码输入错误,请重新输入");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
        //密码加密,调用MD5Utils工具类
        password=MD5Utils.md5(password);
        //调用业务层,查询是否存在User
        UserService userService = new UserServiceImpl();
        User user = userService.getUserBynameAndPassword(username,password);
        //判断用户是否存在
        if (user==null){
            request.setAttribute("msg","对不起,用户名或者密码错误,请重新输入");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
        //如果用户存在,还需要检验激活状态是否激活
        if (user.getState()!=1){
            request.setAttribute("msg","用户未激活,<a href='/Maven_Project_02_war/userActive?code="+user.getCode()+"'>请激活</a>");
        }
        //如果用户激活了,将用户存储到session域中
        request.getSession().setAttribute("user",user);

        //自动登录功能
        //获取自动登录的参数
        String autouser = request.getParameter("autouser");
        //判断是否勾选自动登录
        if (!autouser.equals("AutoUser")){
            //没有勾选,那下次登录直接到登录界面,name浏览器就不存储cookie
            //创建cookie
            Cookie cookie = new Cookie("autouser", "");
            //有效期是0,相当于删除cookie
            cookie.setMaxAge(0);
            //响应给浏览器
            response.addCookie(cookie);

        }else{
            //勾选了,给cookie添加内容
            String content = user.getUsername()+"="+user.getPassword();
            //使用jdk自带的加密工具URLEncoder public static String encode(String s,String enc)
            //参数一:要加密的String,参数二:要加密的字符类型
            content = URLEncoder.encode(content, "utf-8");
            //存储cookie,参数一:cookie的名称,参数二:cookie的内容
            Cookie cookie = new Cookie("autouser", content);
            //设置有效期
            cookie.setMaxAge(30*24*60*60);
            //服务器携带cookie内容给浏览器响应给浏览器
                response.addCookie(cookie);
        }
        //重定向到首页
        response.sendRedirect(request.getContextPath()+"/");
    }
    public void loginOut(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //获取session域
        HttpSession session = request.getSession();
        //移除session中的user
        session.removeAttribute("user");
        //重定向到首页--登录界面
        response.sendRedirect(request.getContextPath()+"/");
    }

}
